package net.pimpas.web.jsf.managedbean.operation;

import java.util.List;

import javax.servlet.ServletContextEvent;

import net.pimpas.operation.exception.OperationException;
import net.pimpas.operation.operation.Operation;
import net.pimpas.operation.operation.OperationAnnotation;
import net.pimpas.web.jsf.managedbean.ManagedBeanAnnotation;
import net.pimpas.web.jsf.managedbean.visitor.ManagedBeanVisitor;

import org.apache.log4j.Logger;
import org.apache.myfaces.config.RuntimeConfig;
import org.apache.myfaces.config.impl.digester.elements.ManagedBean;
import org.apache.myfaces.context.servlet.ServletExternalContextImpl;

@OperationAnnotation(name="ManagedBeanRuntimeOperation")
public class ManagedBeanRuntimeOperation implements Operation<Object> {
	
	private ServletContextEvent context;
	private static Logger logger = Logger.getLogger(ManagedBeanRuntimeOperation.class);

	@SuppressWarnings("unchecked")
	public Object call() throws OperationException {
		if(ManagedBeanVisitor.getManagedBeanClasses().size() == 0) return null;
		
		RuntimeConfig runtime = RuntimeConfig.getCurrentInstance(new ServletExternalContextImpl(this.getContext().getServletContext(), null, null));
		List<Class> clazzs = ManagedBeanVisitor.getManagedBeanClasses();
		ManagedBeanAnnotation ann = null;
		ManagedBean bean = null;
		for(int i=0;i<clazzs.size();i++) {
			bean = new ManagedBean();
			bean.setBeanClass(clazzs.get(i).getName());
			ann = (ManagedBeanAnnotation) clazzs.get(i).getAnnotation(ManagedBeanAnnotation.class);
			bean.setName(ann.beanName());
			bean.setScope(ann.beanScope());
			runtime.addManagedBean(ann.beanName(), bean);
			logger.debug("[ADDED MANAGED BEAN] => NAME: "+bean.getManagedBeanName()+", CLASS: "+bean.getManagedBeanClassName());
		}
		
		return null;
	}

	public ServletContextEvent getContext() {
		return context;
	}

	public void setContext(ServletContextEvent context) {
		this.context = context;
	}

	public void commit() throws OperationException {
		
	}

	public void end() throws OperationException {
		
	}

	public void init(Object... parameters) throws OperationException {
		this.setContext((ServletContextEvent) parameters[0]);
	}

	public void rollBack() throws OperationException {
		
	}

	public void start() throws OperationException {
		
	}
}